import { extend } from 'umi-request';
import { has, isNil, keys, omit } from 'lodash';
import md5 from 'md5';
import { message } from 'antd';
import { history } from 'umi';

export const BASE_URL = '/proxy'; //'http://192.168.124.100:85/admin';

const common = extend({
    prefix: BASE_URL,
    errorHandler(error) {
        console.log(error, '===');
        const { response, data, request } = error;
        console.log(response, data, request);
        console.log(error);
        if (response) {
            console.log(request.url);
            console.log(data);
        } else {
            console.log(`${error.type}: ${error.message}`);
        }
        return Promise.resolve({});
    },
});

/** 按参数名ascii顺序排序，取参数值以&分割，MD5加密生成cs，1&2 */
const salt = (obj: any) => {
    const keys = Object.keys(obj)
        .filter((key) => !isNil(obj[key]))
        .sort();
    console.group('salt');
    console.log(obj);
    console.log(keys);
    console.log(keys.map((i) => obj[i]).join('&'));
    console.log(md5(keys.map((i) => obj[i]).join('&')));
    console.groupEnd();
    return md5(keys.map((i) => obj[i]).join('&'));
};

const saltObject = (obj: any) => {
    const date = Date.now().toString();
    const keyLen = keys(obj).length;
    if (obj instanceof FormData) {
        const field = obj.get('field');
        obj.append('ts', date);
        obj.append(
            'cs',
            salt({ ts: date, ...(field ? { field: field } : {}) }),
        );
        return obj;
    } else if (isNil(obj) || keyLen === 0) return undefined;
    if (keyLen === 1 && has(obj, 'encode') && obj['encode'] === true) {
        return {
            cs: salt({ ts: date }),
            ts: date,
        };
    } else {
        return {
            ...obj,
            cs: salt({ ...obj, ts: date }),
            ts: date,
        };
    }
    return obj;
};

common.interceptors.request.use((url, options) => {
    const params = saltObject(options.params);
    const data = saltObject(options.data);
    let obj = {};
    obj = {
        url,
        options: {
            ...options,
            ...(params ? { params } : {}),
            ...(data ? { data } : {}),
        },
    };
    console.log(obj, '===');
    return obj;
});

common.interceptors.response.use((response) => {
    let data = response.clone().json();
    data.then((res) => {
        if (res.code !== 200) {
            message.error(res.msg || '未知错误信息！！！');
            // history.push('/login');
        }
    });
    return data;
});

export default common;
